﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace ViewStateToDb.Data.SqlServer
{
	internal class SqlServerDataProvider : IDataProvider
	{
		private ViewStateToDbConfiguration _configuration;

		public SqlServerDataProvider(ViewStateToDbConfiguration configuration)
		{
			_configuration = configuration;
		}

		public string GetViewState(Guid viewStateId)
		{
			string viewStateData = null;
			string sql = "select ViewStateData from $ViewState where ViewStateId = @ViewStateId";

			using (var cmd = GetSqlCommand(sql))
			{
				cmd.SetObjectName("ViewState", _configuration.ViewStateDatabaseTable);
				cmd.AddGuid("ViewStateId", viewStateId);

				viewStateData = cmd.GetScalar<string>();
			}

			return viewStateData;
		}

		public void SaveViewState(Guid viewStateId, string viewStateData)
		{
			string sql = @"delete from $ViewState where ViewStateId = @ViewStateId;

							insert into $ViewState(ViewStateId, ViewStateData, Created)
							values(@ViewStateId, @ViewStateData, @Created);";

			using (var cmd = GetSqlCommand(sql))
			{
				cmd.SetObjectName("ViewState", _configuration.ViewStateDatabaseTable);
				cmd.AddGuid("ViewStateId", viewStateId);
				cmd.Parameters.Add("ViewStateData", System.Data.SqlDbType.NVarChar, -1).Value = viewStateData;
				cmd.AddDateTime("Created", DateTime.Now);

				cmd.ExecuteNonQueryOpenCloseConnection();
			}		
		}

		private SqlCommand GetSqlCommand(string sql)
		{
			var cmd = new SqlCommand(sql, new SqlConnection(_configuration.ConnectionString));
			cmd.CommandType = System.Data.CommandType.Text;

			return cmd;
		}
	}
}
